import { _decorator, AudioClip, AudioSource, Component, Director, director, Node } from 'cc';
import { PLAYE_AUDIO } from './Event'
import { AUDIO_EFFECT_ENUM, GAME_EVENT_ENUM } from './Enum';
const { ccclass, property } = _decorator;

@ccclass('MusicManager')
export class MusicManager extends Component {
    @property(AudioClip)
    clickButton: AudioClip = null;
    @property(AudioClip)
    clear: AudioClip = null;
    @property(AudioClip)
    clickBlock: AudioClip = null;
    @property(AudioClip)
    lose: AudioClip = null;
    @property(AudioClip)
    win: AudioClip = null;
    @property(AudioClip)
    mainBgm: AudioClip = null;
    @property(AudioClip)
    gameBgm: AudioClip = null;
    @property(AudioSource)
    audioSource: AudioSource = null;

    protected onLoad(): void {
        //声明常驻的根节点
        director.addPersistRootNode(this.node);
        //注册场景切换事件
        director.on(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
        //管理音效时间注册
        PLAYE_AUDIO.on(GAME_EVENT_ENUM.PLAY_AUDIO, this.onAudioPlay, this);

    }

    onSceneLaunched() {
        let cirrentSceneName = director.getScene()?.name;
        console.log("cirrentSceneName =", cirrentSceneName)
        this.updateBackGroundMusic(cirrentSceneName);

    }

    updateBackGroundMusic(sceneName: string) {
        if (sceneName == "Main") {
            this.audioSource.stop()
            this, this.audioSource.clip = this.mainBgm;
        } else if (sceneName == "Game") {
            this.audioSource.stop()
            this, this.audioSource.clip = this.gameBgm;
        }


        if (this.audioSource.clip) {
            this.audioSource.play();
        }
    }

    protected onDestroy(): void {
        director.off(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
        PLAYE_AUDIO.off(GAME_EVENT_ENUM.PLAY_AUDIO, this.onAudioPlay, this);
    }

    //音效事件回调
    onAudioPlay(type: AUDIO_EFFECT_ENUM) {
        switch (type) {
            case AUDIO_EFFECT_ENUM.CLICKBUTTON:
                this.audioSource.playOneShot(this.clickButton);
                break;
        }

    }

}


